<template>
  <!-- 富文本编辑器 -->
  <div class="editor-border wang-editor">
    <Toolbar
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
      style="border-bottom: 1px solid rgb(220, 223, 230)"
    />
    <Editor
      :defaultConfig="editorConfig"
      :mode="mode"
      v-model="vValue"
      :style="style"
      @onCreated="handleCreated"
      @onChange="handleChange"
      @onDestroyed="handleDestroyed"
      @onFocus="handleFocus"
      @onBlur="handleBlur"
      @customAlert="customAlert"
      @customPaste="customPaste"
    />
  </div>
</template>
<script setup>
import '@wangeditor/editor/dist/css/style.css';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import { i18nChangeLanguage } from '@wangeditor/editor';
import { vModelValue } from '@/utils/hooks.js';
import { ElMessage } from 'element-plus';

i18nChangeLanguage('en');

const props = defineProps({
  modelValue: {
    type: String,
    default: '',
  },
  editorStyle: {
    // 配置editor样式
    type: String,
    default: '',
  },
  toolbarKeys: {
    // 配置工具栏
    type: Array,
    default: () => {
      return [
        'blockquote',
        'header1',
        'header2',
        'header3',
        '|',
        // 'headerSelect',
        'bold',
        'underline',
        'italic',
        'through',
        // 'sub',
        // 'sup',
        'color',
        'bgColor',
        'clearStyle',
        'fontSize',
        'fontFamily',
        '|',
        'bulletedList',
        'numberedList',
        'justifyLeft',
        'justifyRight',
        'justifyCenter',
        '|',

        // 'lineHeight',
        // 'indent',
        // 'delIndent',
        // 'justifyJustify',
        'insertLink',
        'uploadImage',
        'insertTable',
        // 'insertImage',
        // 'deleteImage',
        // 'editImage',
        // 'viewImageLink',
        // 'imageWidth30',
        // 'imageWidth50',
        // 'imageWidth100',
        // 'divider',
        // 'emotion',
        // 'editLink',
        // 'unLink',
        // 'viewLink',
        // 'codeBlock',
        // 'header1',
        // 'header2',
        // 'header3',
        // 'header4',
        // 'header5',
        // 'todo',
        '|',
        'redo',
        'undo',
        '|',
        'fullScreen',
        // 'enter',

        // 'insertTable',
        // 'deleteTable',
        // 'insertTableRow',
        // 'deleteTableRow',
        // 'insertTableCol',
        // 'deleteTableCol',
        // 'tableHeader',
        // 'tableFullWidth',
        // 'insertVideo',
        // 'uploadVideo',
        // 'editVideoSize',
        // 'codeSelectLang',
      ];
    },
  },
  disabled: {
    // 是否禁用
    type: Boolean,
    default: false,
  },
  uploadImageConfig: {
    type: Object,
    default: {
      server: '/api/upload-img', // 上传图片地址
      headers: {},
    },
  },
  mode: {
    // 配置editor样式
    type: String,
    default: 'simple',
  },
});
const emits = defineEmits(['buttonClick', 'update:modelValue']);

const toolbarConfig = computed(() => {
  return {
    toolbarKeys: props.toolbarKeys,
  };
});

const editorConfig = computed(() => {
  return {
    MENU_CONF: {
      uploadImage: {
        maxFileSize: 10 * 1024 * 1024, // 上传最大尺寸10M
        // base64LimitSize: 5 * 1024, // 上传图片尺寸少于5kb，转base64
        allowedFileTypes: ['image/*'],
        fieldName: 'multipartFile',
        ...props.uploadImageConfig,
        onSuccess(file, res) {
          console.log('onSuccess', res);
          if (res.code === '200') {
            insetHtml(`<img src="${res.data}" />`);
          } else {
            ElMessage.error(res.msg);
          }
        },
        onFailed(file, res) {
          console.log('onFailed', res);
          if (res.code === '200') {
            insetHtml(`<img src="${res.data}" />`);
          } else {
            ElMessage.error(res.msg);
          }
        },
        onError(file, err, res) {
          console.error('onError', file, err, res);
          ElMessage.error(res.msg);
        },
      },
    },
  };
});

let editorRef = shallowRef();
const { newValue: key } = vModelValue(props, emits);
let vValue = ref(key || '');

let style = ref(
  `${props.editorStyle || 'min-height: 200px; max-height: 400px;'} overflow-y: auto;`
);

// 模拟 ajax 异步获取内容
onMounted(() => {});

// 组件销毁时，也及时销毁编辑器，重要！
onBeforeUnmount(() => {
  let editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});
// 编辑器回调函数
let handleCreated = editor => {
  editorRef.value = editor; // 记录 editor 实例，重要！
  // 全屏事件触发
  editor.on('fullScreen', () => {
    style.value = '';
    emits('buttonClick', 'fullScreen');
  });
  // 取消全屏事件触发
  editor.on('unFullScreen', () => {
    style.value = `${
      props.editorStyle || 'min-height: 200px; max-height: 400px;'
    } overflow-y: auto;`;
    emits('buttonClick', 'unFullScreen');
  });
};
function handleChange(editor) {
  // console.log('change:', editor.getHtml());
}
function handleDestroyed(editor) {
  // console.log('destroyed', editor);
}
function handleFocus(editor) {
  // 获取焦点
  // console.log('focus', editor);
}

function handleBlur(editor) {
  // 失去焦点
  // console.log('blur', editor);
}

function customPaste(editor, event, callback) {
  // console.log('ClipboardEvent 粘贴事件对象', event);
  // 自定义插入内容
  // editor.insertText('');
  // 返回值（注意，vue 事件的返回值，不能用 return）
  // callback(false); // 返回 false ，阻止默认粘贴行为
  // callback(true) // 返回 true ，继续默认的粘贴行为
}
function customAlert() {}

// 插入html内容
function insetHtml(str) {
  let editor = editorRef.value;
  if (editor == null) return;
  editor.dangerouslyInsertHtml(str);
}

// 重置编辑器内容
function setHtmlText(html) {
  let editor = editorRef.value;
  if (editor == null) return;
  editor.setHtml(html);
}

function printHtml() {
  let editor = editorRef.value;
  if (editor == null) return;
  // console.log(editor.getHtml());
}

// 禁用
function disabledFn() {
  let editor = editorRef.value;
  if (editor == null) return;
  editor.disable();
}

watch(
  () => props.disabled,
  val => {
    if (val) {
      nextTick(() => {
        disabledFn();
      });
    }
  },
  { immediate: true }
);

defineExpose({
  setHtmlText,
  printHtml,
});
</script>
<style lang="scss" scoped>
.editor-border {
  border: 1px solid rgb(220, 223, 230);
  border-radius: 5px;
}
.wang-editor {
  width: 100%;
  :deep() {
    .w-e-toolbar {
      border-radius: 5px;
      svg {
        width: 12px;
        height: 12px;
      }
    }
    .w-e-bar-item {
      padding: 0;
      height: 24px;
    }
    .w-e-bar-item button {
      padding: 0 4px;
      font-size: 12px;
      height: 22px;
      .w-e-bar-item {
        height: 22px;
      }
    }
    .w-e-select-list {
      max-height: 200px;
    }
    .w-e-bar-divider {
      height: 24px;
    }
    .w-e-text-container [data-slate-editor] p {
      margin: 0;
    }
  }
}
.w-e-full-screen-container {
  z-index: 6666;
  box-sizing: border-box;
  // overflow: hidden;
  // :deep() .w-e-scroll {
  //   height: calc(100% - 10px);
  // }
}
</style>
